<template>
	<view class="decision-content">
		<view class="cell-box mt20">
			<view class="cell-title">事件类型</view>
			<view class="cell-content cell-select-item">
				<listSelect v-model="form.evTypeCode" :list="evTypeList"></listSelect>
				<!-- <u-input v-model="form.evTypeCode" type="text" :border="true" :height="60" placeholder="请输入类型" /> -->
			</view>
		</view>

		<view class="cell-box mt20">
			<view class="cell-title">严重程度</view>
			<view class="cell-content cell-select-item">
				<listSelect v-model="form.evLevel" :list="evLevelList"></listSelect>
				<!-- <u-input v-model="form.evLevel" type="text" :border="true" :height="60" placeholder="请输入类型" /> -->
			</view>
		</view>

		<view class="cell-box mt20">
			<view class="cell-title">事件描述</view>
			<view class="cell-content">
				<u-input v-model="form.evDescribe" type="textarea" :border="true" :height="180" placeholder="请输入内容" />
			</view>
		</view>

		<view class="cell-box mt20">
			<view class="cell-title">事件时间</view>
			<!-- @click="showTimeEv" -->
			<view class="cell-content flex-vc">
				<u-icon name="clock" :size="30"></u-icon>
				<text class="ml10"> {{ form.evTime }}</text>
			</view>
		</view>

		<view class="cell-box mt20">
			<view class="cell-title">事件地点</view>
			<!-- @click="changeAddress" -->
			<view class="cell-content">
				<text class="fs26"> {{ form.evLocation }}</text>
			</view>
		</view>

		<view class="cell-box mt20">
			<view class="cell-title">附件</view>
			<view class="cell-content">
				<view></view>
				<uni-file-picker limit="2" title="最多选择2张图片" @select="fileSelect" @delete="fileDelete"></uni-file-picker>
				<uni-file-picker
					limit="1"
					file-mediatype="video"
					title="最多选择1个视频"
					@select="fileSelect"
					@delete="fileDelete"
				></uni-file-picker>
				<!-- <view class="flex-bt">
					<view style="color: #333" class="mt10">最多录制一条语音</view>
					<view style="color: #999; font-size: 14px">{{ recorder ? 1 : 0 }}/1</view>
				</view>
				<uni-button
					type="primary"
					size="mini"
					class="mt10"
					v-show="!recorder"
					@longpress="startRecord"
					@touchend="endRecord"
				>
					按住录制
				</uni-button> -->

				<gurudin-audio
					class="mt10"
					v-if="recorder"
					:duration="recorder.duration"
					:src="recorder.localUrl"
					:name="recorder.name"
					author=""
					ref="audioPlayers"
					@delVideo="delVideo"
				>
				</gurudin-audio>
				<!-- :call="playCall" -->
			</view>
		</view>
		<view class="btnSubmit flex-cc" @click="submit">提交</view>
		<view class="flex-cc mt40">
			<view class="flex-vc" @click="turnTo">
				<text style="color: #a6a6a6">已解决:</text>
				<text style="color: #a6a6a6">{{ MyEventNum.resolvedNum }}条</text>
				<u-icon name="play-right-fill" color="#607589" class="ml10" size="26"></u-icon>
			</view>
			<view class="ml50 flex-vc" @click="turnTo">
				<text style="color: #a6a6a6">未解决:</text>
				<text style="color: #41a4ff">{{ MyEventNum.unresolvedNum }}条</text>
				<u-icon name="play-right-fill" color="#607589" class="ml10" size="26"></u-icon>
			</view>
		</view>
		<u-picker
			mode="time"
			:default-time="form.time"
			v-model="timeShow"
			:params="timeParams"
			@confirm="confirmTime"
		></u-picker>

		<view class="warp-jump" v-show="recordering">
			<view
				class="voice-line-wrap"
				:style="{
					'--line-height': '50rpx',
					'--line-start-color': 'royalblue',
					'--line-end-color': 'indianred'
				}"
			>
				<view class="voice-line one"></view>
				<view class="voice-line two"></view>
				<view class="voice-line three"></view>
				<view class="voice-line four"></view>
				<view class="voice-line five"></view>
				<view class="voice-line six"></view>
				<view class="voice-line seven"></view>
				<view class="voice-line six"></view>
				<view class="voice-line five"></view>
				<view class="voice-line four"></view>
				<view class="voice-line three"></view>
				<view class="voice-line two"></view>
				<view class="voice-line one"></view>
			</view>
			<text class="mt30">录制中</text>
		</view>

		<u-select v-model="addressShow" mode="mutil-column-auto" :list="areaCodeList" @confirm="confirmAddress"></u-select>

		<u-popup v-model="popupShow" mode="bottom" border-radius="14" :closeable="false" close-icon="arrow-down-fill">
			<view class="popup-style">
				<template>
					<view class="video-popup">
						<view class="title flex-cc">录音时长不超过2分钟</view>

						<view class="video-cont flex-cc">
							<view class="upload" v-show="recorderDone"></view>
							<view class="voice">
								<template v-if="!recorderDone">
									<text>{{ recorderTime }}</text>
									<view class="mt20 yuan" @longpress="startRecord" @touchend="endRecord">
										<view></view>
										<image
											v-if="!recordering"
											src="../../../static/image/decision/voice-paly.png"
											mode="widthFix"
											style="width: 50rpx"
										/>
										<view
											v-else
											class="voice-line-wrap"
											:style="{
												'--line-height': '50rpx',
												'--line-start-color': 'royalblue',
												'--line-end-color': 'indianred'
											}"
										>
											<view class="voice-line one"></view>
											<view class="voice-line two"></view>
											<view class="voice-line three"></view>
											<view class="voice-line four"></view>
											<view class="voice-line five"></view>
											<view class="voice-line six"></view>
											<view class="voice-line seven"></view>
											<view class="voice-line six"></view>
											<view class="voice-line five"></view>
											<view class="voice-line four"></view>
											<view class="voice-line three"></view>
											<view class="voice-line two"></view>
											<view class="voice-line one"></view>
										</view>
									</view>
									<view style="color: #a9a9a9" class="mt20 fs26">按住开始录音</view>
								</template>
								<template v-if="recorderDone">
									<text>{{ recorderTime }}</text>
									<audio :src="recorder.localUrl" v-if="recorder" name="本地录音" controls="true"></audio>
									<view class="mt20 yuanPlay" v-show="false">
										<u-icon
											v-show="!recordering"
											:size="50"
											color="#52D2BC"
											name="play-right-fill"
											@click="play(true)"
										></u-icon>
										<u-icon v-show="recordering" :size="50" color="#52D2BC" name="pause" @click="play(false)"></u-icon>
									</view>
									<view style="color: #a9a9a9" class="mt20 fs26">点击播放录音</view>
								</template>
							</view>
							<view class="reload" v-show="recorderDone" @click="reloadRecorder"></view>
						</view>
					</view>
				</template>
			</view>
		</u-popup>

		<!-- <mumu-recorder ref="recorder" @success="handlerSuccess" @error="handlerError"></mumu-recorder> -->
	</view>
</template>
<script>
	import photoIMg from '../../../static/image/decision/photo.png'
	import voiceIMg from '../../../static/image/decision/voice.png'
	import videoIMg from '../../../static/image/decision/video.png'
	import listSelect from '@/components/common/select/listSelect.vue'
	import MumuRecorder from '@/uni_modules/mumu-recorder/components/mumu-recorder/mumu-recorder.vue'

	import sjsbApi from '@/api/yjzh/sjsb.js'
	import { toFormData } from '@/utils/util'
	import moment from 'moment'

	import eventTool from '../../../utils/event'
	export default {
		name: '',
		components: { MumuRecorder, listSelect },
		data() {
			return {
				form: {
					areaCode: '',
					evAreaCode: '',
					evTime: moment().format('YYYY-MM-DD HH:mm:ss'),
					evLocation: '-',
					userId: ''
				},
				// 1= 暴雨 2=积水 3=塌陷 4=滑坡 5=溃堤 6=溃坝
				evTypeList: [
					{
						label: '暴雨',
						value: 1
					},
					{
						label: '积水',
						value: 2
					},
					{
						label: '滑坡崩塌',
						value: 3
					},
					{
						label: '溃堤',
						value: 5
					},
					{
						label: '溃坝',
						value: 6
					}
				],
				evLevelList: [
					{ label: '未定义', value: 0 },
					{ label: '一级', value: 1 },
					{ label: '二级', value: 2 },
					{ label: '三级', value: 3 },
					{ label: '四级', value: 4 }
				],
				timeShow: false,
				timeParams: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: false
				},
				addressShow: false,
				areaCodeList: [],

				typeList: [
					{ name: '图片', type: 'photo', icon: photoIMg },
					{ name: '语音', type: 'voice', icon: voiceIMg },
					{ name: '图片', type: 'video', icon: videoIMg }
				],
				fileList: [],

				popupShow: false,
				recorder: '',
				recorderTime: '00:00',
				recorderDone: false,
				recordering: false,

				MyEventNum: {
					resolvedNum: 0,
					unresolvedNum: 0
				},
				url: ''
			}
		},
		computed: {
			evTypeItem() {
				let item = this.evTypeList.find((el) => {
					return el.value == this.form.evTypeCode
				})
				return item
			}
		},
		mounted() {
			this.getUserInfoData = uni.getStorageSync('getUserInfoData')
			this.form.areaCode = this.getUserInfoData.dept.parentCode
				? this.getUserInfoData.dept.parentCode
				: this.getUserInfoData.dept.code
			this.form.evAreaCode = this.getUserInfoData.dept.code
			this.initPage()
		},
		methods: {
			async initPage() {
				const latlon = await this.$getLocation() //  uni.getStorageSync('latlon')
				const resp = await sjsbApi.getMyEventNum({ userId: this.getUserInfoData.id })
				if (resp.code == 200) {
					this.MyEventNum = resp.data
				}
				this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1', {
					key: 'XENBZ-NF4RU-LMIVC-G7CWJ-ZMMIK-KOFVN',
					location: `${latlon.latitude},${latlon.longitude}`,
					output: 'jsonp'
				})
					.then((res) => {
						this.form.evLocation = res.result.address
					})
					.catch((error) => {
						console.error(error)
						uni.showModal({
							content: '获取地址失败'
						})
					})

				this.form.latitude = latlon.latitude
				this.form.longitude = latlon.longitude

				let res = await eventTool.getTypeJson()
				this.evTypeList = res.evTypeList
				this.evLevelList = res.evLevelList
			},
			showTimeEv() {
				this.timeShow = true
			},
			confirmTime(value, index) {
				this.form.time = `${value.year}-${value.month}-${value.day} ${value.day}:${value.minute}`
			},
			changeAddress() {
				this.addressShow = true
			},
			confirmAddress(value) {},
			changeType(i) {},
			async handlerSuccess(res) {
				this.recorder = res
				this.recorderDone = true
				this.recorder.name = moment().format('DDHHmm') + '.mp3'
				this.fileSelect({ tempFiles: [{ path: res.localUrl, name: this.recorder.name }] })
			},
			handlerError(code) {
				switch (code) {
					case '101':
						uni.showModal({
							content: '当前浏览器版本较低，请更换浏览器使用，推荐在微信中打开。'
						})
						break
					case '201':
						uni.showModal({
							content: '麦克风权限被拒绝，请刷新页面后授权麦克风权限。'
						})
						break
					default:
						uni.showModal({
							content: '未知错误，请刷新页面重试'
						})
						break
				}
			},
			startRecord() {
				this.$refs.recorder.start()
				this.recordering = true
				this.timeindex = 0
				if (this.timer) {
					clearInterval(this.timer)
				}
				this.timer = setInterval(() => {
					this.timeindex++
					this.recorderTime = this.changeTime(this.timeindex)
				}, 1000)
			},
			endRecord() {
				this.$refs.recorder.stop()
				this.recordering = false
				if (this.timer) {
					clearInterval(this.timer)
				}
			},
			reloadRecorder() {
				this.recorderDone = false
				this.recorder = false
				this.recordering = false
				this.timeindex = 0
				this.recorderTime = '00:00'
			},
			delVideo() {
				this.fileDelete({
					tempFile: {
						name: this.recorder.name
					}
				})
				this.recorder = ''
			},
			play(isPlay) {
				if (isPlay) {
					this.recordering = true
				} else {
					this.recordering = false
				}
			},
			changeTime(value) {
				let theTime = value //秒
				let middle = 0 //分
				let hour = 0 //小时
				if (theTime > 59) {
					middle = parseInt(theTime / 60)
					theTime = parseInt(theTime % 60)
				}
				if (middle > 59) {
					hour = parseInt(middle / 60)
					middle = parseInt(middle % 60)
				}
				theTime < 10 ? (theTime = '0' + theTime) : (theTime = theTime)
				middle < 10 ? (middle = '0' + middle) : (middle = middle)
				hour < 10 ? (hour = '0' + hour) : (hour = hour)
				// hour + ':' +
				return middle + ':' + theTime
			},

			async submit() {
				uni.showLoading({
					title: '加载中'
				})
				this.form.evType = this.evTypeItem.label
				this.form.userId = this.getUserInfoData.id
				this.form.userName = this.getUserInfoData.nickName
				this.form.fileUrl = this.folderName
				this.form.areaName = this.getUserInfoData.deptName
				this.form.userPhone = this.getUserInfoData.phone
				const resp = await sjsbApi.add(this.form)
				this.$hideLoading()
				if (resp.code == 200) {
					uni.showToast({
						icon: 'info',
						title: '上报成功'
					})
				} else {
					uni.showToast({
						icon: 'error',
						title: resp.msg
					})
				}
			},
			async fileSelect(data) {
				// data.tempFiles.forEach(async (el) => {
				// 	let file = await this.httpRequest(el.path, el.name)
				// 	this.uploadEv(file)
				// })
				let el = data.tempFiles

				let file = await this.httpRequest(el[0].path, el[0].name)
				console.info(`file:`, file)
				// this.url = file.name + file.type
				await this.uploadEv(file)
				if (data.tempFiles.length > 1) {
					let file2 = await this.httpRequest(el[1].path, el[1].name)
					this.uploadEv(file2)
				}
				//
				// const formData = new FormData()
				// formData.append('file', file)
				// formData.append('folderName', this.folderName || '')
				// const resp = await sjsbApi.uploadReturnUrl(formData)
				// if (resp.code == 200) {
				// 	uni.showToast({
				// 		icon: 'info',
				// 		title: '添加成功'
				// 	})
				// 	this.folderName = resp.data.folderName
				// 	this.fileList.push(resp.data.fileUrl)
				// }
			},
			async uploadEv(file) {
				// console.info(`file:`, file)
				// this.downloadFileStream(file, file.name)
				const formData = new FormData()
				formData.append('file', file)
				formData.append('folderName', this.folderName || '')
				try {
					uni.showLoading({
						title: '正在上传'
					})
					const resp = await sjsbApi.uploadReturnUrl(formData).catch((e) => {
						this.$hideLoading()
					})
					this.$hideLoading()
					if (resp.code == 200) {
						uni.showToast({
							icon: 'info',
							title: '添加成功'
						})
						this.folderName = resp.data.folderName
						this.fileList.push(resp.data.fileUrl)
					} else {
						uni.showToast({
							icon: 'error',
							title: resp.msg
						})
					}
				} catch (error) {
					console.error(error)
					uni.showToast({
						icon: 'error',
						title: '添加失败'
					})
				}
			},
			downloadFileStream(data, fileName) {
				const blob = new Blob([data], { type: 'application/octet-stream' })
				const url = URL.createObjectURL(blob)

				const a = document.createElement('a')
				a.href = url
				a.download = fileName || 'download'
				document.body.appendChild(a)
				a.click()
				document.body.removeChild(a)

				URL.revokeObjectURL(url)
			},
			async fileDelete(data) {
				const index = this.fileList.findIndex((el) => el.indexOf(data.tempFile.name) > -1)
				if (index > -1) {
					const resp = await sjsbApi.deleteFileByUrl({ fileUrl: this.fileList[index] })
					if (resp.code == 200) {
						uni.showToast({
							icon: 'info',
							title: '删除成功'
						})
						this.fileList.splice(index, 1)
					}
				}
			},

			turnTo() {
				// uni.emit('eventPage', {})
				uni.$emit('eventPage', { page: 'report' })
			},
			// async blobUrlToFile(url, filename) {
			// 	const response = await fetch(url)
			// 	const blob = await response.blob()
			// 	return new File([blob], filename)
			// },

			// getFileData(blobList) {
			// 	return new Promise((resolve, reject) => {
			// 		const len = blobList.length
			// 		const filesList = []
			// 		blobList.map(async (src, index) => {
			// 			const file = await this.httpRequest(src)
			// 			console.info(`index:`, index, len)
			// 			filesList.push(file)
			// 			if (index == len - 1) {
			// 				console.info(`filesList:`, filesList)
			// 				resolve(filesList)
			// 			}
			// 		})
			// 	})
			// },
			httpRequest(src, name) {
				let that = this
				return new Promise((resolve, reject) => {
					let xhr = new XMLHttpRequest()
					xhr.open('GET', src, true)
					xhr.responseType = 'blob'
					xhr.onload = function (e) {
						if (this.status == 200) {
							let myBlob = this.response
							let files = new window.File([myBlob], name, { type: myBlob.type }) // myBlob.type 自定义文件名
							resolve(files)
						} else {
							reject(false)
						}
					}
					xhr.send()
				})
			}
		}
	}
</script>
<style lang="less" scoped>
	.decision-content {
		width: 100%;
		height: 100%;
		overflow: auto;
		padding-bottom: 180rpx;
		.cell-box {
			display: flex;
			align-items: center;
			// justify-content: space-between;

			.cell-title {
				width: 150rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				font-size: 26rpx;
				line-height: 34rpx;
				font-weight: 600;
				display: flex;
				align-items: center;

				color: #757575;
			}
			.cell-content {
				width: 500rpx;
				margin-left: 30rpx;
				font-size: 26rpx;
				color: #4e4e4e;
			}
		}
		.cell-select-item {
			width: 100%;
			height: 60rpx;
			border-radius: 4rpx;
			border: 1rpx solid #dcdfe6;
			/deep/ .areaSelect-box {
				position: relative;
				height: 55rpx;
				width: 97%;
				display: flex;
				justify-content: flex-start;
				padding: 0 20rpx;
				padding-left: 45rpx;
			}
		}

		.opera-list {
			display: flex;
			.list-sin {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				width: 140rpx;
				height: 140rpx;
				background: #e4f2ff;
				border: 1rpx solid rgba(0, 133, 255, 0.25);
				border-radius: 4rpx;
				margin-right: 15rpx;
			}
		}
		.btnSubmit {
			width: 636rpx;
			margin: 0 auto;
			height: 75rpx;
			margin-top: 50rpx;

			background: #41a4ff;
			backdrop-filter: blur(15rpx);

			border-radius: 20rpx;
			color: #fff;
			font-size: 30rpx;
		}
	}

	.popup-style {
		width: 750rpx;
		// height: 300rpx;
		background: #fff;

		.video-popup {
			width: 100%;
			// height: 500rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 15rpx;
			.title {
				width: 627rpx;
				height: 60rpx;
				background: rgba(255, 0, 0, 0.11);
				border-radius: 45rpx;
				color: #ff0000;

				font-size: 26rpx;
			}
			.video-cont {
				width: 100%;
				height: 400rpx;
				display: flex;

				.upload {
					min-width: 79rpx;
					min-height: 79rpx;
					background: #edf5ff;
					border-radius: 50%;
				}
				.reload {
					min-width: 79rpx;
					min-height: 79rpx;
					background: #edf5ff;
					border-radius: 50%;
				}
				.voice {
					margin: 0 80rpx;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					.yuan {
						width: 165rpx;
						height: 165rpx;
						background: rgba(65, 164, 255, 0.18);
						border: 2rpx solid #0085ff;
						border-radius: 50%;
						transition: 0.2s height;
						display: flex;
						align-items: center;
						justify-content: center;
					}
					.yuanPlay {
						width: 165rpx;
						height: 165rpx;
						background: rgba(82, 210, 188, 0.19);
						border: 2rpx solid #52d2bc;
						display: flex;
						align-items: center;
						justify-content: center;
						border-radius: 50%;
					}
				}
			}
		}
	}

	.warp-jump {
		position: fixed;
		z-index: 999;
		top: 40%;
		left: 50%;
		transform: translateX(-50%);
		width: 200rpx;
		height: 200rpx;
		background: #fff;
		border-radius: 15rpx;
		box-shadow: 0px 4rpx 30rpx rgba(0, 0, 0, 0.28);
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
	}
	.voice-line-wrap {
		display: flex;
		align-items: center;
		.voice-line {
			width: 5rpx;
			height: 50rpx;
			border-radius: 3rpx;
			margin: 0 5rpx;
		}

		.one {
			animation: wave 0.4s 1s linear infinite alternate;
		}
		.two {
			animation: wave 0.4s 0.9s linear infinite alternate;
		}
		.three {
			animation: wave 0.4s 0.8s linear infinite alternate;
		}
		.four {
			animation: wave 0.4s 0.7s linear infinite alternate;
		}
		.five {
			animation: wave 0.4s 0.6s linear infinite alternate;
		}
		.six {
			animation: wave 0.4s 0.5s linear infinite alternate;
		}
		.seven {
			animation: wave 0.4s linear infinite alternate;
		}
	}

	@keyframes wave {
		0% {
			transform: scale(1, 1);
			background-color: royalblue;
		}
		100% {
			transform: scale(1, 0.2);
			background-color: indianred;
		}
	}
</style>
